import { defineStore } from 'pinia'
import { useUserState, type typeUserInfo } from '@/store/userState'
import * as video from '@/apis/video'

export interface typeWatchHistry {
  vod_id: number
  vod_img: string
  vod_name: string
  currentTime: number
  duration: number
  episode: number
  episode_name: string
  watchTime: number
}
export const useWatchHistry = defineStore('watchHistry', {
  persist: true,
  state: (): {
    list: { [prop: string]: typeWatchHistry }
  } => {
    return {
      list: {}
    }
  },
  getters: {
    getList() {
      const data = []
      for (const index in this.list) data.push(this.list[index])
      data.sort((a, b) => {
        return b.watchTime - a.watchTime
      })
      const sort = [
        { name: '24小时内', list: <typeWatchHistry[]>[] },
        { name: '7天内', list: <typeWatchHistry[]>[] },
        { name: '更早', list: <typeWatchHistry[]>[] }
      ]
      const time_day = new Date().getTime() - 1000 * 60 * 60 * 24
      const time_week = new Date().getTime() - 1000 * 60 * 60 * 24 * 7
      for (const v of data) {
        if (v.watchTime < time_week) sort[2].list.push(v)
        else {
          if (v.watchTime > time_day) sort[0].list.push(v)
          else sort[1].list.push(v)
        }
      }
      return sort
    }
  },
  actions: {
    async add(v: typeWatchHistry) {
      this.list[v.vod_id.toString()] = v
    },
    clear() {
      this.list = {}
    },
    async setListFromServe() {
      const userState = useUserState()
      try {
        const userInfo = await userState.getUserInfo()
        if (userInfo) {
          video.getVideoHistry().then(res => {
            this.list = {}
            for (const v of res.data.data) {
              this.list[v.vod_id.toString()] = v
            }
          })
        }
      } catch (error) {
        //失败
      }
    }
  }
})
